跳到主要内容

Go 网络包 httputil-打印网络请求

打印网络请求

注意这个工具一般用在调试时,它的执行效率不高

打印服务端收到的请求

Golang 提供了一个 DumpRequest 工具可以用来输出请求的内容

import (
"log"
"net/http"
"net/http/httputil"
)

func main() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
dump, _ := httputil.DumpRequest(r, true) // 第二个参数是否显示 body
log.Printf("代理请求数据: %s", dump)

/* 设置应答头 */
w.Header().Set("Content-Type", "application/json")

/* 设置状态码 */
w.WriteHeader(201)

/* 设置应答体 */
w.Write([]byte("{}"))
})
http.ListenAndServe(":1280", nil)
}

请求

curl -d'login=emma&password=123' -X POST http://localhost:1280

Golang 控制台输出

2021/12/20 14:18:01 代理请求数据: POST / HTTP/1.1
Host: localhost:1280
Accept: */*
Content-Length: 25
Content-Type: application/x-www-form-urlencoded
User-Agent: curl/7.64.0

login=emma&password=123

DumpRequest 返回 req 的和被服务端接收到时一样的有线表示,可选地包括请求的主体,用于 debug。

本函数在语义上是无操作的,但为了转储请求主体,他会读取主体的数据到内存中,并将 req.Body 修改为指向内存中的拷贝。

打印客户端请求

上面的 DumpRequest 用作打印服务端收到的的 Request,当需要自己去请求时则通过这个 DumpRequestOut 打印

DumpRequestOut 类似 DumpRequest,但会包括标准 http.Transport 类型添加的头域,如 User-Agent。

func main() {
req, err := http.NewRequest(http.MethodGet, "https://www.google.com", nil)
if err != nil {
return
}
requestDump, _ := httputil.DumpRequestOut(req, false)
log.Printf("打印请求: %s", requestDump)
}

Golang 控制台输出

2021/12/20 14:41:08 打印请求: GET / HTTP/1.1
Host: www.google.com
User-Agent: Go-http-client/1.1
Accept-Encoding: gzip

打印客户端响应

func main() {
resp, err := http.Get("https://www.baidu.com")
if err != nil {
return
}
defer resp.Body.Close()

dump, _ := httputil.DumpResponse(resp, false)
log.Printf("打印响应头: %s", dump)
}

Golang 控制台输出

2021/12/20 14:58:35 打印响应头: HTTP/1.1 200 OK
Content-Length: 227
Accept-Ranges: bytes
Cache-Control: no-cache
Connection: keep-alive
Content-Type: text/html
Date: Mon, 20 Dec 2021 06:58:35 GMT
P3p: CP=" OTI DSP COR IVA OUR IND COM "
P3p: CP=" OTI DSP COR IVA OUR IND COM "
Pragma: no-cache
Server: BWS/1.1
Set-Cookie: BD_NOT_HTTPS=1; path=/; Max-Age=300
Set-Cookie: BIDUPSID=90CA49C500F16CCDF8320520F1A2093E; expires=Thu, 31-Dec-37 23:55:55 GMT; max-age=2147483647; path=/; domain=.baidu.com
Set-Cookie: PSTM=1639983515; expires=Thu, 31-Dec-37 23:55:55 GMT; max-age=2147483647; path=/; domain=.baidu.com
Set-Cookie: BAIDUID=90CA49C500F16CCD83C727248FF791B7:FG=1; max-age=31536000; expires=Tue, 20-Dec-22 06:58:35 GMT; domain=.baidu.com; path=/; version=1; comment=bd
Strict-Transport-Security: max-age=0
Traceid: 1639983515045629082614963470251705031207
X-Frame-Options: sameorigin
X-Ua-Compatible: IE=Edge,chrome=1

References

Simple and Powerful ReverseProxy in Go